package com.kingsoft.dc.khaos.module.spark.util

import com.kingsoft.dc.khaos.extender.meta.model.ds.OracleConnect
import com.kingsoft.dc.khaos.util.Logging

import java.sql.{Connection, DriverManager, Statement}
import java.util.Properties


/**
 * Created by czc on 2020/10/27.
 */
object OracleUtils extends Logging{
  private val driver = "oracle.jdbc.driver.OracleDriver"

  /**
   * 根据连接参数获取oracle的connection
   * @param url
   * @param oracleConnect
   * @return
   */
  def getOracleConnection(url:String ,oracleConnect:OracleConnect): Connection = {
    val prop = getPropbyConnInfo(oracleConnect)
    DriverManager.getConnection(url,prop);
  }

  def getPropbyConnInfo(oracleConnectop:OracleConnect): Properties = {
    val prop = new Properties
    prop.put("driver", driver)
    prop.put("user", oracleConnectop.getUsername)
    prop.put("password", oracleConnectop.getPassword)
    val osuser = System.getProperty("user.name")
    prop.put("oracle.jdbc.v$session.osuser",osuser.substring(0,30))
    prop
  }

  /** 通过不同的连接方式获取oracle对应的jdbcUrl，host中将ip:port拼接在了一起*/
  def getOracleConnectTypeURL(host: String, instanceName: String, connectType: String): String = {
    var url: String = null
    connectType match {
      case "SID" => {
        url = s"jdbc:oracle:thin:@$host:$instanceName"
      }
      case "ServiceName" => {
        url = s"jdbc:oracle:thin:@//$host/$instanceName"
      }
      case "RAC" => {
        val hostArray = host.split(",")
        var address = ""
        for (i <- 0 until hostArray.length) {
          //(ADDRESS=(PROTOCOL=TCP)(HOST=x.x.x.x)(PORT=1521))
          address += s"(ADDRESS=(PROTOCOL=TCP)(HOST=${hostArray(i).split(":")(0)})(PORT=${hostArray(i).split(":")(1)}))"
        }
        //jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=x.x.x.x)(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=x.x.x.y)(PORT=1521)))(LOAD_BALANCE=yes)(FAILOVER=ON)(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=db.domain)))
        url = s"jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=${address})(LOAD_BALANCE=yes)(FAILOVER=ON)(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=$instanceName)))"
      }
      case _ =>
    }
    url
  }

  def executeSql(url:String ,prop:Properties,sql:String) {
    var conn:Connection = null
    var stmt:Statement = null
    try{
      Class.forName(driver);
      conn = DriverManager.getConnection(url,prop);
      stmt = conn.createStatement()
      log.info("执行sql："+ sql)
      stmt.execute(sql)
    }finally {
      if(stmt != null){
        stmt.close()
      }
      if(conn!=null)
        conn.close()
    }
  }

  def close(conn :Connection): Unit ={
    if(conn!=null)
      conn.close();
  }

}
